from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from decimal import Decimal

from .serializers import OrderSettlementSerializer, SaveOrderSerializer
from goods.models import SKU


class SaveOrderView(CreateAPIView):
    """
    保存订单视图
    """
    serializer_class = SaveOrderSerializer
    permission_classes = [IsAuthenticated]


class OrderSettlementView(APIView):
    """订单详情页面"""

    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        请求订单详情页面
        :param request:
        :return:
        """
        user = request.user

        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)

        cart_dict = {}
        for sku_id in cart_selected:
            cart_dict[int(sku_id)] = int(redis_cart[sku_id])

        skus = SKU.objects.filter(id__in=cart_dict.keys())
        for sku in skus:
            sku.count = cart_dict[sku.id]

        freight = Decimal('10.00')

        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})

        return Response(serializer.data)

